﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace reactiveBT.Coroutines
{
    /// <summary>
    /// A handle to a (potentially running) coroutine.
    /// </summary>
    public class CoroutineHandle
    {
        /// <summary>
        /// Reference to the routine's runner.
        /// </summary>
        //public CoroutineRunner Runner;

        /// <summary>
        /// Reference to the routine's enumerator.
        /// </summary>
        private Coroutine coroutine;

        /// <summary>
        /// Construct a coroutine. Never call this manually, only use return values from Coroutines.Run().
        /// </summary>
        /// <param name="coroutine">The routine's enumerator.</param>
        public CoroutineHandle(Coroutine coroutine)
        {
            //Runner = runner;
            this.coroutine = coroutine;

        }

        /// <summary>
        /// Stop this coroutine if it is running.
        /// </summary>
        /// <returns>True if the coroutine was stopped.</returns>
        public bool Stop()
        {
            //return IsRunning && Runner.Stop(Enumerator);
            if (coroutine.state != CoroutineState.Dead)
            {
                coroutine.state = CoroutineState.Dead;
                return true;
            }
            return false;
        }

        /// <summary>
        /// A routine to wait until this coroutine has finished running.
        /// </summary>
        /// <returns>The wait enumerator.</returns>
        public bool Yield()
        {
            //if (Enumerator != null)
            //    while (Runner.IsRunning(Enumerator))
            //        yield return null;
            if (coroutine.state == CoroutineState.Running || coroutine.state == CoroutineState.Ready)
            {
                coroutine.state = CoroutineState.Suspended;
                return true;
            }
            return false;
        }

        public bool Resume()
        {
            if (coroutine.state == CoroutineState.Suspended)
            {
                coroutine.state = CoroutineState.Ready;
                return true;
            }
            return false;
        }

        public CoroutineState State
        {
            get
            {
                return coroutine.state;
            }
        }
    }
}